import React, { useContext, useEffect, useRef, useState } from 'react';
import type { MenuProps, ConfigProviderProps, RadioChangeEvent } from 'antd';
import { Breadcrumb, Layout, Menu, theme, ConfigProvider, Button, message } from 'antd';
import style from '../css/Index.module.scss'
import RealTimeClock from '../components/CurrentTime'
import { Badge, Radio } from 'antd'
import { Outlet, useLocation, useNavigate } from 'react-router';
import {
    ScheduleOutlined,
    MessageOutlined,
    SettingOutlined,
    SkinOutlined,
    PoweroffOutlined,
    MenuUnfoldOutlined,
    MenuFoldOutlined
} from '@ant-design/icons';
import enUS from 'antd/locale/en_US';
import zhCN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { context } from '../components/AppProvider';
type Locale = ConfigProviderProps['locale'];

dayjs.locale('en');

const { Header, Content, Sider } = Layout;
// type MenuItem = Required<MenuProps>['items'][number];
// 导航数据
// const Navs: MenuItem[] = [
//     {
//         key: '/index/indexcontent',
//         icon: <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E7%B3%BB%E7%BB%9F%E6%A1%86%E6%9E%B6/u1095.svg" alt="" />,
//         label: '首页',
//     },
//     {
//         key: '/index/patientmangent',
//         icon: <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E7%B3%BB%E7%BB%9F%E6%A1%86%E6%9E%B6/u1095.svg" alt="" />,
//         label: '患者管理',
//         children: [
//             { key: '/index/patientmangent/PatientRegistration', label:'患者登记' },
//             { key: '/index/patientmangent/PatientLists', label: '患者列表' ,},
//         ],
//     },
//     {
//         key: '/index/Registrationmanagement',
//         icon: <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E7%B3%BB%E7%BB%9F%E6%A1%86%E6%9E%B6/u1095.svg" alt="" />,
//         label: '挂号管理',
//         children: [
//             { key: '/index/Registrationmanagement/Outpatientregistration', label: '门诊挂号' },
//             { key: '/index/Registrationmanagement/Registrationinquiry', label: '挂号查询' },
//             { key: '/index/Registrationmanagement/Blacklistmanagement', label: '黑名单管理' },
//         ],
//     },
//     {
//         key: '/index/WorkforceManagement',
//         icon: <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E7%B3%BB%E7%BB%9F%E6%A1%86%E6%9E%B6/u1095.svg" alt="" />,
//         label: '排班管理',
//         children: [
//             { key: '/index/WorkforceManagement/Doctorscheduling', label: '医生排班' },
//             { key: '/index/WorkforceManagement/CopyScheduling', label: '复制排班' },
//             { key: '/index/WorkforceManagement/SchedulingSettings', label: '排班设置' },
//             { key: '/index/WorkforceManagement/Schedulinginquiry', label: '排班查询' },
//         ],
//     },
//     {
//         key: '/index/statisticsquery',
//         icon: <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E7%B3%BB%E7%BB%9F%E6%A1%86%E6%9E%B6/u1095.svg" alt="" />,
//         label: '统计查询',
//         children: [
//             { key: '/index/statisticsquery/Patientfilingstatistics', label: '患者建档统计' },
//             { key: '/index/statisticsquery/Outpatientregistrationstatistics', label: '门诊挂号统计' },
//         ],
//     },
//     {
//         key: '/index/systemmanagement',
//         icon: <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E7%B3%BB%E7%BB%9F%E6%A1%86%E6%9E%B6/u1095.svg" alt="" />,
//         label: '系统管理',
//         children: [
//             { key: '/index/systemmanagement/Dictionarymanaged', label: '字典管理' },
//             { key: '/index/systemmanagement/Parameterconfiguration', label: '参数配置' },
//             {
//                 key: '/index/systemmanagement/Logmanagement',
//                 label: '日志管理',
//                 children: [
//                     { key: '/index/systemmanagement/Logmanagement/LoginLog', label: '登录日志' },
//                     { key: '/index/systemmanagement/Logmanagement/OperationLog', label: '操作日志' }
//                 ]
//             },
//         ],
//     },
// ];


const App: React.FC = () => {
    const {
        token: { colorBgContainer, borderRadiusLG },
    } = theme.useToken();
    const [count, setCount] = useState(100);  //消息数量
    //设置
    const [bol, setBol] = useState(false)
    const setup = () => {
        setBol(!bol)
        setCount(100)
    }
    
    const {meaus} = useContext(context)

    // 侧边导航点击
    const {pathname} = useLocation()    //获取location中的数据
    // 获取当前选中的menu菜单的值
    const findOpenKeys = (key:string) => {
        const result :string[] = []

        const findInfo = (arr:any) =>{
            arr.forEach((item:any)=>{
                if(key.includes(item.key)){
                    result.push(item.key)
                    if(item.children){
                        findInfo(item.children)
                    }
                }
            })
        }

        findInfo(meaus)

        return result
    }
    const temOpenKeys = findOpenKeys(pathname)
    const navigate=useNavigate()
    const [current, setCurrent] = useState('/index/indexcontent');
    const contentRef = useRef<HTMLDivElement>(null);
    const onClick: MenuProps['onClick'] = (e) => {
        setCurrent(e.key);
        navigate(e.key)
    };
    useEffect(() => {
        // 每次组件挂载或更新时滚动到顶部
        if (contentRef.current) {
          contentRef.current.scrollTop = 0;
        }else{
            window.scrollTo(0,0)
        }
      }, [current]); 
    
    
    // 面包屑导航数据操作
    const [breadcrumbs,setBreadcrumbs]= useState<any>([])
    
    useEffect(()=>{
        setBreadcrumbs(findDeepPath(pathname))
        setCurrent(pathname)
    },[pathname])
    const BreadcrumbItems=[
        {
            key:'/index/patientmangent',
            title:<a href='/index/patientmangent/PatientRegistration' className={style.beradtitle}>患者管理</a>,
            children:[
                {
                    key:'/index/patientmangent/PatientRegistration',
                    title:<a href='/index/patientmangent/PatientRegistration' className={style.beradtitle}>患者登记</a>,
                },
                {
                    key:'/index/patientmangent/PatientLists',
                    title:<a href='/index/patientmangent/PatientLists' className={style.beradtitle}>患者列表</a>,
                    Children:[
                        {
                            key:'/index/patientmangent/PatientLists/PatientDetail',
                            title:<a href='/index/patientmangent/PatientLists/PatientDetail'>患者详情</a>
                        }
                    ]
                }
            ]
        },
        {
            key: '/index/Registrationmanagement',
            title: <a href="/index/Registrationmanagement/Outpatientregistration" className={style.beradtitle}>挂号管理</a>,
            children: [
                { key: '/index/Registrationmanagement/Outpatientregistration', title: <a href='/index/Registrationmanagement/Outpatientregistration' className={style.beradtitle}>门诊挂号</a> },
                { key: '/index/Registrationmanagement/Registrationinquiry', title: <a href='/index/Registrationmanagement/Registrationinquiry' className={style.beradtitle}>挂号查询</a> ,
                Children:[
                    {
                        key:'/index/Registrationmanagement/Registrationinquiry/Registerdetails',
                        title:<a href='/index/Registrationmanagement/Registrationinquiry/Registerdetails'>挂号详情</a>
                    }
                ]
                },
                { key: '/index/Registrationmanagement/Blacklistmanagement', title: <a href='/index/Registrationmanagement/Blacklistmanagement' className={style.beradtitle}>黑名单管理</a> },
            ],
        },
        {
            key: '/index/WorkforceManagement',
            title: <a href="/index/WorkforceManagement/Doctorscheduling" className={style.beradtitle}>排班管理</a>,
            children: [
                { key: '/index/WorkforceManagement/Doctorscheduling', title: <a href="/index/WorkforceManagement/Doctorscheduling" className={style.beradtitle}>医生排班</a> },
                { key: '/index/WorkforceManagement/CopyScheduling', title: <a href="/index/WorkforceManagement/CopyScheduling" className={style.beradtitle}>复制排班</a> },
                { key: '/index/WorkforceManagement/SchedulingSettings', title: <a href="/index/WorkforceManagement/SchedulingSettings" className={style.beradtitle}>排班设置</a> },
                { key: '/index/WorkforceManagement/Schedulinginquiry', title: <a href="/index/WorkforceManagement/Schedulinginquiry" className={style.beradtitle}>排班查询</a> },
            ],
        },
        {
            key: '/index/statisticsquery',
            title: <a href="/index/statisticsquery/Patientfilingstatistics" className={style.beradtitle}>统计查询</a>,
            children: [
                { key: '/index/statisticsquery/Patientfilingstatistics', title: <a href="" className={style.beradtitle}>患者建档统计</a> },
                { key: '/index/statisticsquery/Outpatientregistrationstatistics', 
                title: <a href="/index/statisticsquery/Outpatientregistrationstatistics" className={style.beradtitle}>门诊挂号统计</a> },
            ],
        },
        {
            key: '/index/systemmanagement',
            title: <a href="/index/systemmanagement/Dictionarymanaged" className={style.beradtitle}>系统管理</a>,
            children: [
                { key: '/index/systemmanagement/Dictionarymanaged', title: <a href="/index/systemmanagement/Dictionarymanaged" className={style.beradtitle}>字典管理</a> },
                { key: '/index/systemmanagement/Parameterconfiguration', title: <a href="" className={style.beradtitle}>参数配置</a> },
                {
                    key: '/index/systemmanagement/Logmanagement',
                    title: <a href="" className={style.beradtitle}>日志管理</a>,
                    children: [
                        { key: '/index/systemmanagement/Logmanagement/LoginLog', title: <a href="" className={style.beradtitle}>登录日志</a> },
                        { key: '/index/systemmanagement/Logmanagement/OperationLog', title: <a href="" className={style.beradtitle}>操作日志</a> }
                    ]
                },
            ],
        },
        
    ]
    // 获取当前选中的数据所有父节点
    const findDeepPath = (key:string) =>{
        const result:any = []   //处理完所有的menu数据称为一个一维数组
        const findInfo = (arr:any) =>{
            arr.forEach((item:any) => {
                const {children,...info} = item
                result.push(info);
                if(children){
                    findInfo(children)  //递归处理子节点
                }
            });
        }
        findInfo(BreadcrumbItems)
        const tmpData = result.filter((item:any)=>key.includes(item.key))
        if(tmpData.length>0){
            return [{title:<a href='/index/indexcontent' className={style.beradtitle}>首页</a>,key:'/index/indexcontent'},...tmpData]
        }
        return []
       
    }
    // 侧边导航展开与收回
    const [collapsed, setCollapsed] = useState(false);
    //语言切换
    const [locale, setLocal] = useState<Locale>(zhCN);
    const changeLocale = (e: RadioChangeEvent) => {
        const localeValue = e.target.value;
        setLocal(localeValue);
        if (!localeValue) {
            dayjs.locale('en');
        } else {
            dayjs.locale('zh-cn');
        }
    };
    const schedus = () => {
        navigate('/index/WorkforceManagement/Doctorscheduling')
    }
    // 退出登录
    const Logout = () => {
        const loadingInstance = message.loading('Action in progress..', 0); // 0 表示不会自动关闭
        setTimeout(() => {
            // 关闭加载中的提示
            loadingInstance();
            // 显示成功提示
            message.success(`退出登录成功！`);
            navigate('/login')
            localStorage.removeItem('token')
        }, 2000);
        
    }

    return (
        <ConfigProvider locale={locale}
        >
            <Layout>
                <Header style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                    position: 'sticky',
                    top: 0,
                    zIndex: 999,
                    width: '100%',
                }} className={style.header}>
                    <div className={style.Header_left}>
                        <div className={style.demo_logo}>
                            <div className={style.combination_logo}>
                                <div className={style.trianle}></div>
                                <div className={style.rectangle}></div>
                                <div className={style.ellipse}></div>
                            </div>
                            <span className={style.system_name}>门诊挂号系统</span>
                        </div>
                        <Button
                            type="text"
                            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                            onClick={() => setCollapsed(!collapsed)}
                            style={{
                                fontSize: '15px',
                                marginLeft: 27,
                                width: 15,
                                height: 15,
                            }}
                        />
                        <div style={{ marginLeft: '32px' }}><RealTimeClock></RealTimeClock></div>
                    </div>
                    <div className={style.Header_right}>
                        {/* 国际化切换 */}
                        <Radio.Group value={locale} onChange={changeLocale} className={style.national}>
                            <Radio.Button key="en" value={enUS}>
                                English
                            </Radio.Button>
                            <Radio.Button key="cn" value={zhCN}>
                                中文
                            </Radio.Button>
                        </Radio.Group>
                        <div className={style.badeg}>
                            <Badge count={count} size="small" offset={[5, 0]} className={style.badges}>
                                <MessageOutlined className={style.message} />
                            </Badge>
                            <p className={style.texts}>消息</p>
                        </div>
                        <div className={style.badeg} onClick={()=>schedus()}>
                            <ScheduleOutlined className={style.message} />
                            <p className={style.texts}>排班日历</p>
                        </div>
                        <div className={style.badeg}>
                            <SkinOutlined className={style.message} />
                            <p className={style.texts}>换肤</p>
                        </div>
                        <div className={style.badeg + ' ' + style.setup} onClick={() => setup()}>
                            <SettingOutlined className={style.message} />
                            <p className={style.texts}>设置</p>
                            <ul className={bol ? style.perpson_popup : style.active}>
                                <li>
                                    <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E7%B3%BB%E7%BB%9F%E6%A1%86%E6%9E%B6/u1194.svg" alt="" />
                                    <span>系统切换</span>
                                </li>
                                <li>
                                    <div className={style.disableimg + " " + style.Department}>
                                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E7%B3%BB%E7%BB%9F%E6%A1%86%E6%9E%B6/u1203.svg" alt="" />
                                    </div>
                                    <span>科室切换</span>
                                </li>
                                <li>
                                    <div className={style.disableimg + " " + style.theme}>
                                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E7%B3%BB%E7%BB%9F%E6%A1%86%E6%9E%B6/u1199.svg" alt="" />
                                    </div>
                                    <span>主题设置</span>
                                </li>
                            </ul>
                        </div>
                        <div className={style.userinfo}>
                            <div className={style.uesravater}>
                                <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E8%AE%BE%E8%AE%A1%E7%BB%84%E4%BB%B6/u133.svg" alt="" />
                                <div className={style.userstate}>
                                    <div className={style.statebg}></div>
                                    <div className={style.statecircle}></div>
                                </div>
                            </div>
                            <p className={style.username}>管理员</p>
                            {/* <LogoutOutlined className={style.Logout} /> */}
                            <PoweroffOutlined className={style.Logout}  onClick={()=>Logout()}/>
                        </div>
                    </div>
                </Header>
                <Layout>
                    {/* 左侧导航 */}
                    <Sider width={236} style={{ background: colorBgContainer }} collapsed={collapsed}>
                        <Menu
                            mode="inline"
                            onClick={onClick}
                            defaultSelectedKeys={temOpenKeys}
                            defaultOpenKeys={temOpenKeys}
                            // selectedKeys={[current]}
                            style={{
                                height: '92%', borderRight: 0,
                                maxWidth: 236,
                                position: 'fixed',
                                top: 60,
                                bottom: 0,
                                overflow: 'auto',
                                scrollbarWidth:'none'
                            }}
                            items={meaus}
                            theme='light'
                        />
                    </Sider>
                    {/* 内容区域 */}
                    <Layout style={{ padding: '0 24px 24px' }}>
                        <Breadcrumb 
                            items={breadcrumbs}
                            style={{ margin: '16px 0' }}
                            className={temOpenKeys[0] == '/index/indexcontent' ? style.Breadcrumb : ''}
                        >
                        </Breadcrumb>
                        <Content
                            style={{
                                minHeight: 280,
                                width: 1145,
                                borderRadius: borderRadiusLG,
                            }}
                            className={style.content}
                        >
                            <Outlet></Outlet>
                        </Content>
                    </Layout>
                </Layout>
            </Layout>
        </ConfigProvider>
    );
};

// export default App;
function Index() {
    return (
        <>
            <App></App>
        </>
    );
}

export default Index;